package com.servlet;

import com.entity.Book;
import com.service.BookService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Objects;

@WebServlet("/addBook")
public class AddBookServlet extends HttpServlet {
    BookService bookService = new BookService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/admin/add_book.jsp").forward(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookid = req.getParameter("bookid");//姓名
        String bookname = req.getParameter("bookname");//姓名
        String author = req.getParameter("author");//作者
        String publish = req.getParameter("publish");//出版社
        //数字
        String bookcount = req.getParameter("bookcount");//数量
        long i = Long.parseLong(bookcount);
        String booktype = req.getParameter("booktype");//类型
        if (bookname != null || author != null || publish != null || bookcount != null || booktype != null) {

            Book book = new Book();
            book.setBookname(bookname);
            book.setAuthor(author);
            book.setPublish(publish);
            book.setBookcount(i);
            book.setBooktype(booktype);

            try {
//
                if(!bookid.isEmpty()&&Objects.nonNull(bookid)){
                    Book bookById = bookService.getBookById(Long.parseLong(bookid));
                    book = bookService.updataBook(book,bookById.getBookid());
                }else {
                    bookService.save(book);
                }
                req.setAttribute("book", book);
                req.getRequestDispatcher("/BookSearch").forward(req, resp);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        } else {
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }

    }
}
